<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { axiosrnewmedical } from '@/http/axiosRead';
// import { axioswnewmedical } from '@/http/axiosWrite';

// 处方记录接口
interface PrescriptionDetail {
  id: number;
  applicationId: number;
  itemType: number;
  itemTypeName: string;
  itemId: number;
  itemName: string;
  quantity: number;
  unitPrice: number;
  amount: number;
}

interface Prescription {
  id: number;
  hospitalId: number;
  hospitalName: string;
  userId: number;
  userName: string;
  applicationTime: string;
  status: number;
  statusName: string;
  totalAmount: number;
  applyReason: string;
  auditorId: number;
  auditorName: string;
  auditTime: string;
  rejectReason: string;
  paymentTime: string;
  cancelTime: string;
  details: PrescriptionDetail[];
}

// 患者接口
interface Patient {
  id: number;
  accountId: number;
  name: string;
  sex: boolean;
  sexText: string;
  idCard: string;
  idCardMasked: string;
  dateOfBirth?: string;
  age?: number;
  contactInfo?: string;
  currentAddress?: string;
  infectiousDiseaseHistory?: string;
  geneticDiseaseInfo?: string;
  createPeople?: string;
  createTime?: string;
  updatePeople?: string;
  updateTime?: string;
}

const router = useRouter();
// 状态变量
const activeTab = ref('全部'); // 当前选中的标签
const prescriptions = ref<Prescription[]>([]); // 处方记录列表
const loading = ref(false);
const currentUserId = ref<number>(0); // 当前用户ID
const currentPatient = ref<string>(''); // 当前患者
const patientId = ref<string>(''); // 患者ID卡号
const patients = ref<Patient[]>([]); // 患者列表
const showPatientPopup = ref(false); // 控制就诊人弹窗显示

const tabs = [
  { name: '全部', status: null },
  { name: '待审核', status: 0 },
  { name: '已审核', status: 1 },
  { name: '已支付', status: 3 },
  { name: '已取消', status: 4 }
];

// 根据状态筛选处方
const filteredPrescriptions = computed(() => {
  if (activeTab.value === '全部') {
    return prescriptions.value;
  } else {
    const status = tabs.find(tab => tab.name === activeTab.value)?.status;
    return prescriptions.value.filter(p => status === null || p.status === status);
  }
});

// 获取处方记录
const fetchPrescriptions = async () => {
  loading.value = true;
  try {
    // 从localStorage获取用户ID，默认为1
    const userId = localStorage.getItem('userId') || '1';
    currentUserId.value = Number(userId);
    
    const response = await axiosrnewmedical.get('/Prescription/GetPrescriptionApplications', {
      params: {
        userId: userId,
        pageIndex: 1,
        pageSize: 50,
        includeDetails: true
      }
    });
    
    if (response.data.code === 200 && response.data.data) {
      prescriptions.value = response.data.data;
    } else {
      console.error('获取处方记录失败:', response.data.msg);
      // 添加示例数据
      prescriptions.value = [
        {
          id: 1,
          hospitalId: 1,
          hospitalName: '四川省保健院北苑',
          userId: 1,
          userName: '王小珂',
          applicationTime: '2020-01-01T10:30:20Z',
          status: 0,
          statusName: '待审核',
          totalAmount: 201.00,
          applyReason: '头晕、发热',
          auditorId: 0,
          auditorName: '',
          auditTime: '',
          rejectReason: '',
          paymentTime: '',
          cancelTime: '',
          details: [
            {
              id: 1,
              applicationId: 1,
              itemType: 1,
              itemTypeName: '药品',
              itemId: 1,
              itemName: '新冠预防中药（正常人群）',
              quantity: 1,
              unitPrice: 11.80,
              amount: 11.80
            },
            {
              id: 2,
              applicationId: 1,
              itemType: 1,
              itemTypeName: '药品',
              itemId: 2,
              itemName: '云南白药胶囊 0.5g*20片',
              quantity: 1,
              unitPrice: 10.08,
              amount: 10.08
            },
            {
              id: 3,
              applicationId: 1,
              itemType: 2,
              itemTypeName: '检查',
              itemId: 1,
              itemName: '动态心电图',
              quantity: 1,
              unitPrice: 150.00,
              amount: 150.00
            },
            {
              id: 4,
              applicationId: 1,
              itemType: 3,
              itemTypeName: '检验',
              itemId: 1,
              itemName: '血常规',
              quantity: 1,
              unitPrice: 29.12,
              amount: 29.12
            }
          ]
        },
        {
          id: 2,
          hospitalId: 1,
          hospitalName: '四川省保健院北苑',
          userId: 1,
          userName: '王小珂',
          applicationTime: '2020-01-01T10:30:20Z',
          status: 1,
          statusName: '已审核',
          totalAmount: 201.00,
          applyReason: '头晕、发热',
          auditorId: 1,
          auditorName: '张医生',
          auditTime: '2020-01-02T10:30:20Z',
          rejectReason: '',
          paymentTime: '',
          cancelTime: '',
          details: [
            {
              id: 5,
              applicationId: 2,
              itemType: 2,
              itemTypeName: '检查',
              itemId: 1,
              itemName: '动态心电图',
              quantity: 1,
              unitPrice: 150.00,
              amount: 150.00
            },
            {
              id: 6,
              applicationId: 2,
              itemType: 3,
              itemTypeName: '检验',
              itemId: 1,
              itemName: '血常规',
              quantity: 1,
              unitPrice: 29.12,
              amount: 29.12
            },
            {
              id: 7,
              applicationId: 2,
              itemType: 1,
              itemTypeName: '药品',
              itemId: 1,
              itemName: '新冠预防中药（正常人群）',
              quantity: 1,
              unitPrice: 11.80,
              amount: 11.80
            }
          ]
        },
        {
          id: 3,
          hospitalId: 1,
          hospitalName: '四川省保健院北苑',
          userId: 1,
          userName: '王小珂',
          applicationTime: '2020-01-01T10:30:20Z',
          status: 2,
          statusName: '审核驳回',
          totalAmount: 201.00,
          applyReason: '头晕、发热',
          auditorId: 1,
          auditorName: '张医生',
          auditTime: '2020-01-02T10:30:20Z',
          rejectReason: '您所开的项目必须与您的历史诊断相符',
          paymentTime: '',
          cancelTime: '',
          details: [
            {
              id: 8,
              applicationId: 3,
              itemType: 2,
              itemTypeName: '检查',
              itemId: 1,
              itemName: '动态心电图',
              quantity: 1,
              unitPrice: 150.00,
              amount: 150.00
            },
            {
              id: 9,
              applicationId: 3,
              itemType: 3,
              itemTypeName: '检验',
              itemId: 1,
              itemName: '血常规',
              quantity: 1,
              unitPrice: 29.12,
              amount: 29.12
            },
            {
              id: 10,
              applicationId: 3,
              itemType: 1,
              itemTypeName: '药品',
              itemId: 1,
              itemName: '新冠预防中药（正常人群）',
              quantity: 1,
              unitPrice: 11.80,
              amount: 11.80
            }
          ]
        },
        {
          id: 4,
          hospitalId: 1,
          hospitalName: '四川省保健院北苑',
          userId: 1,
          userName: '王小珂',
          applicationTime: '2020-01-01T10:30:20Z',
          status: 3,
          statusName: '已支付',
          totalAmount: 201.00,
          applyReason: '头晕、发热',
          auditorId: 1,
          auditorName: '张医生',
          auditTime: '2020-01-02T10:30:20Z',
          rejectReason: '',
          paymentTime: '2020-01-03T10:30:20Z',
          cancelTime: '',
          details: [
            {
              id: 11,
              applicationId: 4,
              itemType: 2,
              itemTypeName: '检查',
              itemId: 1,
              itemName: '动态心电图',
              quantity: 1,
              unitPrice: 150.00,
              amount: 150.00
            },
            {
              id: 12,
              applicationId: 4,
              itemType: 3,
              itemTypeName: '检验',
              itemId: 1,
              itemName: '血常规',
              quantity: 1,
              unitPrice: 29.12,
              amount: 29.12
            },
            {
              id: 13,
              applicationId: 4,
              itemType: 1,
              itemTypeName: '药品',
              itemId: 1,
              itemName: '新冠预防中药（正常人群）',
              quantity: 1,
              unitPrice: 11.80,
              amount: 11.80
            }
          ]
        },
        {
          id: 5,
          hospitalId: 1,
          hospitalName: '四川省保健院北苑',
          userId: 1,
          userName: '王小珂',
          applicationTime: '2020-01-01T10:30:20Z',
          status: 4,
          statusName: '已取消',
          totalAmount: 201.00,
          applyReason: '头晕、发热',
          auditorId: 0,
          auditorName: '',
          auditTime: '',
          rejectReason: '',
          paymentTime: '',
          cancelTime: '2020-01-02T10:30:20Z',
          details: [
            {
              id: 14,
              applicationId: 5,
              itemType: 2,
              itemTypeName: '检查',
              itemId: 1,
              itemName: '动态心电图',
              quantity: 1,
              unitPrice: 150.00,
              amount: 150.00
            },
            {
              id: 15,
              applicationId: 5,
              itemType: 3,
              itemTypeName: '检验',
              itemId: 1,
              itemName: '血常规',
              quantity: 1,
              unitPrice: 29.12,
              amount: 29.12
            },
            {
              id: 16,
              applicationId: 5,
              itemType: 1,
              itemTypeName: '药品',
              itemId: 1,
              itemName: '新冠预防中药（正常人群）',
              quantity: 1,
              unitPrice: 11.80,
              amount: 11.80
            }
          ]
        }
      ];
    }
  } catch (error) {
    console.error('获取处方记录请求错误:', error);
    // 添加示例数据（与上面相同）
    prescriptions.value = [
      // ... 示例数据（与上面相同）
    ];
  } finally {
    loading.value = false;
    
    // 如果当前没有选中患者，但有处方数据，则需要设置患者信息
    if (!currentPatient.value && prescriptions.value.length > 0) {
      // 从当前用户ID查找对应患者
      const patient = patients.value.find(p => p.id === currentUserId.value);
      if (patient) {
        currentPatient.value = patient.name;
        patientId.value = patient.idCardMasked;
      } else {
        // 如果找不到患者信息，使用处方中的用户名
        currentPatient.value = prescriptions.value[0].userName;
      }
    }
  }
};

// 获取患者列表
const fetchPatients = async () => {
  try {
    // 从localStorage获取用户ID，默认为1
    const accountId = localStorage.getItem('userId') || '1';
    
    // 使用支持多患者的API路径
    const response = await axiosrnewmedical.get(`/Patient/GetPatientsByAccountId`, {
      params: { 
        accountId: accountId,
        includeDeleted: false
      }
    });
    
    if (response.data.code === 200) {
      // 直接使用data字段获取患者列表
      patients.value = response.data.data || [];
      
      console.log('获取到的患者列表:', patients.value);
      
      // 如果有患者信息，设置当前患者
      if (patients.value.length > 0) {
        selectPatient(patients.value[0]);
      }
    } else {
      console.error('获取患者列表失败:', response.data.msg);
      // 添加示例数据
      patients.value = [
        {
          id: 1,
          accountId: 1,
          name: '王小珂',
          sex: true,
          sexText: '男',
          idCard: '510122199001010000',
          idCardMasked: '5101****0000',
        },
        {
          id: 2,
          accountId: 1,
          name: '李玲玲',
          sex: false,
          sexText: '女',
          idCard: '510122199501010000',
          idCardMasked: '5101****0000',
        }
      ];
      
      // 如果有患者信息，设置当前患者
      if (patients.value.length > 0) {
        selectPatient(patients.value[0]);
      }
    }
  } catch (error) {
    console.error('获取患者列表请求错误:', error);
    // 添加示例数据
    patients.value = [
      {
        id: 1,
        accountId: 1,
        name: '王小珂',
        sex: true,
        sexText: '男',
        idCard: '510122199001010000',
        idCardMasked: '5101****0000',
      },
      {
        id: 2,
        accountId: 1,
        name: '李玲玲',
        sex: false,
        sexText: '女',
        idCard: '510122199501010000',
        idCardMasked: '5101****0000',
      }
    ];
    
    // 如果有患者信息，设置当前患者
    if (patients.value.length > 0) {
      selectPatient(patients.value[0]);
    }
  }
};

// 选择患者
const selectPatient = (patient: Patient) => {
  console.log('选择患者:', patient);
  currentPatient.value = patient.name;
  patientId.value = patient.idCardMasked;
  currentUserId.value = patient.id;
  
  console.log('设置后的患者信息:', {
    currentPatient: currentPatient.value,
    patientId: patientId.value,
    currentUserId: currentUserId.value
  });
  
  // 关闭弹窗
  showPatientPopup.value = false;
  
  // 重新获取处方记录
  fetchPrescriptions();
};

// 切换患者
const switchPatient = () => {
  // 显示患者选择弹窗
  showPatientPopup.value = true;
};

// 添加就诊人
const addPatient = () => {
  // 跳转到添加就诊人页面
  router.push('/patient-view');
};

const goBack = () => {
  router.back();
};

// 切换标签
const switchTab = (tab: string) => {
  activeTab.value = tab;
};

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return '';
  const date = new Date(dateTimeStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
};

// 获取处方项目列表摘要（前三个项目，用逗号分隔，末尾用省略号）
const getPrescriptionSummary = (prescription: Prescription) => {
  if (!prescription.details || prescription.details.length === 0) return '';
  const items = prescription.details.map(d => d.itemName);
  if (items.length <= 3) {
    return items.join('、');
  } else {
    return `${items.slice(0, 3).join('、')}...`;
  }
};

// 处理按钮点击事件
const handleButtonClick = (prescription: Prescription, action: string) => {
  if (action === 'cancel') {
    // 处理取消申请
    console.log('取消申请:', prescription.id);
  } else if (action === 'pay') {
    // 处理去支付
    console.log('去支付:', prescription.id);
    // 跳转到支付页面，传递prescriptionApplicationId参数
    router.push(`/payment?prescriptionApplicationId=${prescription.id}`);
  } else if (action === 'detail') {
    // 处理查看详情
    console.log('查看详情:', prescription.id);
    // 跳转到详情页面
    router.push(`/prescription-detail?id=${prescription.id}`);
  }
};

// 页面可见性变化时刷新数据
const handleVisibilityChange = () => {
  if (!document.hidden) {
    // 页面重新变为可见时，刷新数据
    fetchPrescriptions();
  }
};

onMounted(() => {
  // 获取患者列表
  fetchPatients();
  // 监听页面可见性变化
  document.addEventListener('visibilitychange', handleVisibilityChange);
});

// 组件卸载时移除监听器
onUnmounted(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange);
});
</script>

<template>
  <div class="prescription-record-page">
    <van-nav-bar
      title="开单记录"
      left-arrow
      @click-left="goBack"
    />
    
    <div class="tab-container">
      <div class="tab-list">
        <div 
          v-for="tab in tabs" 
          :key="tab.name"
          class="tab-item"
          :class="{ active: activeTab === tab.name }"
          @click="switchTab(tab.name)"
        >
          {{ tab.name }}
        </div>
      </div>
    </div>
    
    <div class="patient-info">
      <div class="patient-data">
        <span class="patient-name">{{ currentPatient }}</span>
        <span class="patient-id">{{ patientId }}</span>
      </div>
      <div class="switch-patient" @click="switchPatient">
        <van-icon name="user-circle-o" />
        <span>切换</span>
      </div>
    </div>
    
    <van-loading v-if="loading" class="loading-spinner" />
    
    <div class="record-list" v-else>
      <div v-for="prescription in filteredPrescriptions" :key="prescription.id" class="record-item">
        <div class="record-header">
          <div class="blue-line"></div>
          <div class="record-title">{{ getPrescriptionSummary(prescription) }}</div>
          <div class="record-status" :class="`status-${prescription.status}`">
            {{ prescription.statusName }}
          </div>
        </div>
        
        <div class="record-info">
          <div class="info-item">
            <div class="info-label">申请医院</div>
            <div class="info-value">{{ prescription.hospitalName }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">申请时间</div>
            <div class="info-value">{{ formatDateTime(prescription.applicationTime) }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">开单金额</div>
            <div class="info-value price">￥{{ prescription.totalAmount.toFixed(2) }}</div>
          </div>
          
          <!-- 审核驳回原因 -->
          <div class="reject-reason" v-if="prescription.status === 2">
            <div class="reject-title">驳回原因</div>
            <div class="reject-content">{{ prescription.rejectReason }}</div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="record-actions" v-if="prescription.status !== 4">
            <!-- 待审核状态 - 显示取消申请和去支付按钮 -->
            <template v-if="prescription.status === 0">
              <button 
                class="action-btn cancel-btn"
                @click="handleButtonClick(prescription, 'cancel')"
              >
                取消申请
              </button>
              <button 
                class="action-btn pay-btn"
                @click="handleButtonClick(prescription, 'pay')"
              >
                去支付
              </button>
            </template>
            
            <!-- 已审核状态 - 显示去支付按钮 -->
            <button 
              v-if="prescription.status === 1" 
              class="action-btn pay-btn"
              @click="handleButtonClick(prescription, 'pay')"
            >
              去支付
            </button>
            
            <!-- 已支付状态 -->
            <button 
              v-if="prescription.status === 3" 
              class="action-btn detail-btn"
              @click="handleButtonClick(prescription, 'detail')"
            >
              查看详情
            </button>
          </div>
          
          <!-- 已取消状态 -->
          <div class="cancelled-tag" v-if="prescription.status === 4">
            已全部加载
          </div>
        </div>
      </div>
      
      <div class="no-records" v-if="filteredPrescriptions.length === 0">
        暂无开单记录
      </div>
    </div>
  </div>
  
  <!-- 患者选择弹窗 -->
  <van-popup v-model:show="showPatientPopup" position="bottom" round :style="{ height: '45%' }">
    <div class="patient-popup">
      <div class="popup-header">
        <span class="popup-title">选择就诊人</span>
        <van-icon name="cross" @click="showPatientPopup = false" />
      </div>
      
      <div class="popup-content">
        <div 
          v-for="patient in patients" 
          :key="patient.id"
          class="patient-item"
          @click="selectPatient(patient)"
        >
          <div class="patient-name">{{ patient.name }}</div>
          <div class="patient-id">{{ patient.idCardMasked }}</div>
        </div>
      </div>
      
      <div class="popup-footer">
        <button class="add-patient" @click="addPatient">添加就诊人</button>
      </div>
    </div>
  </van-popup>
</template>

<style scoped>
.prescription-record-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.tab-container {
  background-color: #ffffff;
  padding: 0 10px;
}

.tab-list {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
}

.tab-item {
  padding: 12px 15px;
  font-size: 14px;
  color: #333;
  position: relative;
  cursor: pointer;
}

.tab-item.active {
  color: #1989fa;
  font-weight: 500;
}

.tab-item.active::after {
  content: "";
  position: absolute;
  bottom: -1px;
  left: 15px;
  right: 15px;
  height: 2px;
  background-color: #1989fa;
}

.patient-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 12px 15px;
  margin-bottom: 10px;
}

.patient-data {
  display: flex;
  align-items: center;
}

.patient-name {
  font-size: 16px;
  font-weight: 500;
  margin-right: 8px;
}

.patient-id {
  font-size: 14px;
  color: #999;
}

.switch-patient {
  display: flex;
  align-items: center;
  color: #1989fa;
  font-size: 14px;
}

.switch-patient .van-icon {
  margin-right: 5px;
}

.record-list {
  padding: 0 10px;
}

.record-item {
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 10px;
  overflow: hidden;
}

.record-header {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  border-bottom: 1px solid #f5f5f5;
}

.blue-line {
  width: 3px;
  height: 16px;
  background-color: #1989fa;
  margin-right: 8px;
  border-radius: 3px;
}

.record-title {
  flex: 1;
  font-size: 15px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.record-status {
  font-size: 13px;
  padding: 3px 8px;
  border-radius: 10px;
}

.status-0 {
  color: #ff9900;
  background-color: #fff9e6;
}

.status-1 {
  color: #1989fa;
  background-color: #e6f1ff;
}

.status-2 {
  color: #f56c6c;
  background-color: #fef0f0;
}

.status-3 {
  color: #67c23a;
  background-color: #f0f9eb;
}

.status-4 {
  color: #909399;
  background-color: #f4f4f5;
}

.record-info {
  padding: 10px 15px 15px;
}

.info-item {
  display: flex;
  margin-top: 8px;
}

.info-label {
  width: 70px;
  font-size: 14px;
  color: #666;
}

.info-value {
  flex: 1;
  font-size: 14px;
  color: #333;
}

.price {
  color: #f56c6c;
  font-weight: 500;
}

.reject-reason {
  margin-top: 12px;
  padding: 10px;
  background-color: #fef0f0;
  border-radius: 4px;
}

.reject-title {
  font-size: 14px;
  color: #f56c6c;
  margin-bottom: 5px;
}

.reject-content {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}

.record-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.action-btn {
  padding: 6px 15px;
  border-radius: 15px;
  font-size: 14px;
  border: none;
  cursor: pointer;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.pay-btn {
  background-color: #1989fa;
  color: #fff;
}

.detail-btn {
  background-color: #1989fa;
  color: #fff;
}

.cancelled-tag {
  text-align: center;
  color: #999;
  font-size: 13px;
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px solid #f5f5f5;
}

.no-records {
  text-align: center;
  padding: 40px 0;
  color: #999;
  font-size: 14px;
}

.loading-spinner {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

/* 患者选择弹窗 */
.patient-popup {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.popup-title {
  font-size: 18px;
  font-weight: 500;
}

.popup-content {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

.patient-item {
  padding: 15px;
  background-color: #f5f9ff;
  margin: 10px 15px;
  border-radius: 8px;
  cursor: pointer;
}

.patient-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 5px;
}

.patient-id {
  font-size: 14px;
  color: #999;
}

.popup-footer {
  padding: 15px;
  border-top: 1px solid #f5f5f5;
}

.add-patient {
  width: 100%;
  background-color: #1989fa;
  color: white;
  border: none;
  border-radius: 25px;
  padding: 12px 0;
  font-size: 16px;
  cursor: pointer;
}
</style> 